# 姓名:刘豹
#  开发时间: 2021/4/28 14:19
import cv2  #导入opencv模块
import numpy as np
import matplotlib.pyplot as plt
from math import pi
#print("Hellow word!")     #打印“Hello word！”，验证模块导入成功

def features (a):
    img = cv2.imread(a)  #导入图片，图片放在程序所在目录
    #cv2.namedWindow("imagshow", 2)   #创建一个窗口
    #cv2.imshow('imagshow', img)    #显示原始图片

    grayImage=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #转换为灰度图


    # Prewitt算子
    kernelx = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]], dtype=int)
    kernely = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]], dtype=int)
    x = cv2.filter2D(grayImage, cv2.CV_16S, kernelx)
    y = cv2.filter2D(grayImage, cv2.CV_16S, kernely)
    # 转uint8
    absX = cv2.convertScaleAbs(x)
    absY = cv2.convertScaleAbs(y)
    Prewitt = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)
    #cv2.imshow('Prewitt',Prewitt)


    #使用局部阈值的大津算法进行图像二值化
    # Prewitt = cv2.adaptiveThreshold(Prewitt,255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV,55, 1)

    thresh=35

    ret,Prewitt = cv2.threshold(Prewitt,thresh,255,cv2.THRESH_BINARY) #输入灰度图，输出二值图

    #cv2.imshow('binary',Prewitt)
    element = cv2.getStructuringElement(cv2.MORPH_CROSS,(1, 1))#形态学去噪
    Prewitt=cv2.morphologyEx(Prewitt,cv2.MORPH_OPEN,element)  #开运算去噪
    #  cv2.MORPH_OPEN 先进行腐蚀操作，再进行膨胀操作


    contours, hierarchy = cv2.findContours(Prewitt,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)  #轮廓检测函数
    cv2.drawContours(Prewitt,contours,-1,(120,0,0),2)  #绘制轮廓

    count=0
    #ares_avrg=0  # 米粒平均
    margin =0
    #遍历找到的所有米粒
    X_train = np.empty(shape=[0,9])
    for cont in contours:

        ares = cv2.contourArea(cont)#计算包围性状的面积
        if ares<25:   #过滤面积小于10的形状
           continue
        if ares>500:
           continue
        rect = cv2.minAreaRect(cont)
        box = np.int0(cv2.boxPoints(rect))
        rect_w, rect_h = int(rect[1][0]) + 1, int(rect[1][1]) + 1
        h, w = img.shape[:2]
        if rect_w <= rect_h:
           x, y = box[1][0], box[1][1]
           M2 = cv2.getRotationMatrix2D((x, y), rect[2], 1)
           rotated_image = cv2.warpAffine(img, M2,(w,h))
           rotated_canvas = rotated_image[y:y + rect_h + margin + 1, x:x + rect_w + margin + 1]
        else:
           x, y = box[2][0], box[2][1]  # 旋转中心
           M2 = cv2.getRotationMatrix2D((x, y), rect[2] + 90, 1)
           rotated_image = cv2.warpAffine(img, M2,(w,h))
           rotated_canvas = rotated_image[y:y + rect_w + margin + 1, x:x + rect_h + margin + 1]
        if rotated_canvas.shape[0]==0 or rotated_canvas.shape[1]==0:
           continue
        Perimeter = cv2.arcLength(cont, True)  # 计算目标啊的周长
        Complexity = (Perimeter ** 2 / (4 * pi * ares))  # 计算目标的复杂度
        dutycycle= ares/(rect[1][0]*rect[1][1]) #计算害虫的占空比
        count += 1  # 总体计数加1
        #cv2.imshow("dst", rotated_canvas)
        #print(count)
        #cv2.waitKey(0)
        b,g,r = cv2.split(rotated_canvas)
        b_mean=np.mean(b)
        g_mean=np.mean(g)
        r_mean=np.mean(r)
        rotated_canvas_HSV = cv2.cvtColor(rotated_canvas, cv2.COLOR_BGR2HSV)
        h,s,v=cv2.split(rotated_canvas_HSV)
        h_mean=np.mean(h)
        s_mean=np.mean(s)
        v_mean=np.mean(v)
        rotated_canvas_LAB = cv2.cvtColor(rotated_canvas, cv2.COLOR_BGR2LAB)
        L,A,B=cv2.split(rotated_canvas_LAB)
        L_mean=np.mean(L)
        A_mean=np.mean(A)
        B_mean=np.mean(B)
        X_train=np.append(X_train,[[b_mean,g_mean,r_mean,h_mean,s_mean,v_mean,L_mean,A_mean,B_mean]],axis=0)
        #print(X_train)
        #print(X_train.shape)
    #print(X_train.shape)
    return X_train
#features('test2.jpg')







